import {designPage} from "@peryl/react-compose";
import {AutoTable, Button, createSimpleDate, Icon, PageCard, PageCardContent, Plc, PlcDate, PlcNumber, PlcOv, PlcTextarea, Segment, SegmentGroup, Space, Tooltip, useContextmenuOptions, useTableFilter} from "plain-design";
import {useTableOption} from "../../modules/plain-design/useTableOption";
import {ov} from "../../modules/plain-design/ov";
import {openOptionValueManager} from "../../modules/plain-design/openOptionValueManager";


export default designPage(() => {

  const contextmenu = useContextmenuOptions();

  const option = useTableOption({
    url: '/stock_log',
    fill: true,
    size: 'mini',
    param: {
      orders: [{ field: 'seq', desc: true }, { field: 'logDate', desc: true }]
    },
    tableProps: {
      virtual: true,
      virtualRowType: 'realIndex',
      border: true,
    },
  });

  /*从今天开始往前找num个工作日日期*/
  const getWorkDates = (num: number): string[] => {
    const ret: string[] = [];
    const date = new Date();
    date.setMonth(date.getMonth(), date.getDate() + 1);
    while (ret.length < num) {
      date.setMonth(date.getMonth(), date.getDate() - 1);
      const day = date.getDay();
      if (day == 0 || day == 6) {continue;}
      ret.push(createSimpleDate(date)["YYYY-MM-DD"]);
    }
    return ret;
  };

  const getMonthDates = () => {
    const startDate = new Date();
    startDate.setMonth(startDate.getMonth(), 1);
    const endDate = new Date();
    endDate.setMonth(endDate.getMonth() + 1, 0);
    return { startDate: createSimpleDate(startDate)["YYYY-MM-DD"], endDate: createSimpleDate(endDate)["YYYY-MM-DD"] };
  };

  const getYearDates = () => {
    const startDate = new Date();
    startDate.setFullYear(startDate.getFullYear(), 0, 1);
    const endDate = new Date();
    endDate.setFullYear(startDate.getFullYear() + 1, 11, 0);
    return { startDate: createSimpleDate(startDate)["YYYY-MM-DD"], endDate: createSimpleDate(endDate)["YYYY-MM-DD"] };
  };

  const dateFilterOptions: {
    label: string,
    val: string,
    default?: true,
    value: { dates: string[] } | { startDate: string, endDate: string } | null
  }[] = [
    { label: '1日', val: '1', value: { dates: getWorkDates(1) } },
    { label: '3日', val: '3', value: { dates: getWorkDates(3) } },
    { label: '5日', val: '5', value: { dates: getWorkDates(5) } },
    { label: '10日', val: '10', value: { dates: getWorkDates(10) } },
    { label: '本月', val: 'month', value: getMonthDates() },
    { label: '今年', val: 'year', value: getYearDates() },
    { label: '全部', val: 'all', value: null, default: true, },
  ];

  const filterStock = useTableFilter<string>({
    option,
    display: (val) => `股票: ${ov.getNameByTypeAndCodeComputed('STOCK', val)}`,
    getQueryParam: (val) => ({ queries: [{ id: 'filter_stock', field: 'stockCode', value: val, operator: '=' }] }),
  });
  const filterDate = useTableFilter<string>({
    option,
    noClear: true,
    defaultValue: dateFilterOptions.find(i => i.default)?.val,
    display: (val) => `日期筛选: ${dateFilterOptions.find(i => i.val == val)!.label}`,
    getQueryParam: (val) => {
      const filterValue = dateFilterOptions.find(i => i.val === val)?.value;
      if (filterValue == null) {return {};}
      if ('dates' in filterValue) {
        const { dates } = filterValue;
        return { queries: [{ id: 'filter_date', field: 'logDate', value: dates, operator: 'in' }] };
      } else {
        const { startDate, endDate } = filterValue;
        return {
          queries: [
            { id: 'filter_date_start', field: 'logDate', value: startDate, operator: '>=' },
            { id: 'filter_date_end', field: 'logDate', value: endDate, operator: '<=' },
          ]
        };
      }
    },
  });

  option.hooks.onContextmenuCell.use(({ node, plc, e }) => {
    if (!!plc.props.field && plc.props.field == 'stockCode') {
      e.preventDefault();
      contextmenu.open({
        x: e.clientX, y: e.clientY, options: [{
          label: '只看该股', handler: () => {
            filterStock.model.set(node.data.stockCode);
            filterDate.reload();
          },
        }]
      });
    }
  });

  const handler = {
    managerStocks: () => {
      openOptionValueManager('STOCK', { title: '股票管理', onClose: () => option.methods.pageMethods.load() });
    },
  };

  return () => <>
    <PageCard full size="mini">
      <PageCardContent>
        <Space style={{ display: 'flex', justifyContent: 'space-between' }}>
          <Space style={{ display: 'flex', alignItems: 'center' }}>
            <span>日期筛选: </span>
            <SegmentGroup modelValue={filterDate.model.get()} onUpdateModelValue={filterDate.model.set} onChange={filterDate.reload}>
              {dateFilterOptions.map(item => (<Segment label={item.label} val={item.val} key={item.val}/>))}
            </SegmentGroup>
            <Tooltip message="本页面用来测试虚拟滚动下的合并单元格功能，将页大小切换为100以上可自动开启虚拟滚动"><Icon icon="pi-info-circle"/></Tooltip>
          </Space>
          <Button icon="pi-settings" label="股票管理" onClick={handler.managerStocks}/>
        </Space>
      </PageCardContent>
      <PageCardContent full noPadding>
        <AutoTable option={option}>
          <Plc title="股票代码" field="stockCode" width={90} autoRowSpan/>
          <PlcOv title="股票名称" field="stockCode" ov="STOCK" required overflowTooltip autoRowSpan/>
          <PlcDate title="日期" field="logDate" required autoRowSpan/>
          <PlcNumber title="明盘资金(亿)" field="darkFund" required/>
          <PlcNumber title="暗盘资金(亿)" field="openFund" required/>
          <Plc title="主力净资金(亿)" field="name" v-slots={{
            normal: ({ row }) => {
              let { darkFund, openFund } = row;
              darkFund = darkFund == null ? null : Number(darkFund);
              openFund = openFund == null ? null : Number(openFund);
              if (darkFund == null || isNaN(darkFund) || openFund == null || isNaN(openFund)) {return '';}
              return darkFund + openFund;
            },
          }}/>
          <PlcOv title="预测涨跌" field="forecast" tip="预测下个交易日涨跌" ov="STOCK_FORECAST"/>
          <PlcOv title="预测结果" field="forecastResult" ov="STOCK_FORECAST_RESULT"/>
          <PlcTextarea title="预测说明" field="forecastComments" overflowTooltip/>
          <PlcTextarea title="当天笔记" field="thatDateComments" overflowTooltip/>
          <PlcTextarea title="复盘结论" field="reviewComments" overflowTooltip/>
        </AutoTable>
      </PageCardContent>
    </PageCard>
  </>;
});
